﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Resources;
using System.Linq;

namespace BloggingServicePinger
{

    public partial class DoBlogPingForm : Form
    {
        ResourceManager LocRM = new ResourceManager("BloggingServicePinger.DoBlogPingForm", typeof(DoBlogPingForm).Assembly);

        public DoBlogPingForm()
        {
            //System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
            InitializeComponent();
            if (File.Exists(BloggingServicePinger.Properties.Settings.Default.serverListUrl))
            {
                Stream serverStream = File.OpenRead(BloggingServicePinger.Properties.Settings.Default.serverListUrl);
                string[] servers = LoadServersToPing(serverStream);
                System.Windows.Forms.ListView.ListViewItemCollection lviCol = new ListView.ListViewItemCollection(listView1);
                foreach (string s in servers)
                {
                    lviCol.Add(new ListViewItem(s, 5));
                }
                serverStream.Close();
                label_count.Text = listView1.Items.Count.ToString();
            }
            listView1.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        private void button_edit_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath);
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr != DialogResult.OK)
            {
                textBox_serverlist.Text = string.Empty;
                return;
            }
            textBox_serverlist.Text = openFileDialog1.FileName;
            listView1.Items.Clear();
            string[] servers = LoadServersToPing(openFileDialog1.OpenFile());
            System.Windows.Forms.ListView.ListViewItemCollection lviCol = new ListView.ListViewItemCollection(listView1);
            foreach (string s in servers)
            {
                lviCol.Add(new ListViewItem(s, 5));
            }
            openFileDialog1.Dispose();
            label_count.Text = listView1.Items.Count.ToString();
        }

        private string[] LoadServersToPing(Stream fileStream)
        {
            StreamReader sr = new StreamReader(fileStream);
            string[] serverList = sr.ReadToEnd().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            List<string> returnList = new List<string>();
            for (int i = 0; i < serverList.Count(); i++)
            {
                if (!Regex.IsMatch(serverList[i], "http://[^,;]*", RegexOptions.IgnoreCase))
                {
                    continue;
                }
                returnList.Add(serverList[i]);
            }
            return returnList.ToArray<string>();
        }

        private void PingerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            BloggingServicePinger.Properties.Settings.Default.Size = this.Size;
            BloggingServicePinger.Properties.Settings.Default.Save();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            ListViewItem[] items = e.Argument as ListViewItem[];

            ListView lv = new ListView();
            List<ListViewItem> itemList = new List<ListViewItem>();

            for (int i = 0; i < items.Count(); i++)
            {
                if (backgroundWorker1.CancellationPending)
                {
                    return;
                }

                string server = items[i].Text;
                int percentage = (i * 100) / items.Count();
                HttpPingerClass pingServer = new HttpPingerClass(this.ProductName, server, textBox_blogUrl.Text, textBox_title.Text);
                ListViewItem item;
                switch (pingServer.HttpStatusCode)
                {
                    case System.Net.HttpStatusCode.OK:
                        item = new ListViewItem(server, 0);
                        break;
                    case System.Net.HttpStatusCode.RequestTimeout:
                    case System.Net.HttpStatusCode.Forbidden:
                        item = new ListViewItem(server, 1);
                        break;
                    case System.Net.HttpStatusCode.Found:
                        item = new ListViewItem(server, 4);
                        break;
                    default:
                        item = new ListViewItem(server, 2);
                        break;
                }
                item.ToolTipText = string.Format("HTTP Status:{0} - {1}\n{2}", (int)pingServer.HttpStatusCode, pingServer.HttpStatusCode.ToString(), pingServer.PingResponse);
                item.SubItems.Add(string.Format("{0} - {1}", (int)pingServer.HttpStatusCode, pingServer.HttpStatusCode.ToString()));
                item.SubItems.Add(pingServer.PingResponse);
                itemList.Add(item);
                backgroundWorker1.ReportProgress(percentage, (ListViewItem)item.Clone());
            }
            e.Result = itemList.ToArray<ListViewItem>();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            ListViewItem item = e.UserState as ListViewItem;
            ListViewItem updateItem = listView1.FindItemWithText(item.Text);
            if (updateItem != null)
            {
                updateItem.ImageIndex = item.ImageIndex;
                for (int i = 1; i < item.SubItems.Count; i++)
                {
                    updateItem.SubItems.Add(item.SubItems[i]);
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show(LocRM.GetString("DoneText"));
            button_ping.Text = LocRM.GetString("PingText");
            progressBar1.Value = 0;

            ListViewItem[] itemList = e.Result as ListViewItem[];
            if (itemList != null)
            {
                listView1.Items.Clear();
                listView1.Items.AddRange(itemList);
            }
        }


        private void button_ping_Click(object sender, EventArgs e)
        {

            if (!backgroundWorker1.IsBusy)
            {
                button_ping.Text = LocRM.GetString("CancelText");
                ListViewItem[] items = new ListViewItem[listView1.Items.Count];
                listView1.Items.CopyTo(items, 0);
                backgroundWorker1.RunWorkerAsync(items);
            }
            else
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listView1.SelectedItems)
            {
                listView1.Items.Remove(item);
                label_count.Text = listView1.Items.Count.ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult dr = saveFileDialog1.ShowDialog();
            if (dr != DialogResult.OK)
                return;

            TextWriter writer = new StreamWriter(saveFileDialog1.OpenFile());
            foreach (ListViewItem item in listView1.Items)
            {
                writer.WriteLine(item.Text);
            }

            writer.Close();
            textBox_serverlist.Text = saveFileDialog1.FileName;
            BloggingServicePinger.Properties.Settings.Default.serverListUrl = saveFileDialog1.FileName;
        }

        private void PingerForm_Load(object sender, EventArgs e)
        {
            this.Size = BloggingServicePinger.Properties.Settings.Default.Size;

        }
    }
}
